package com.xm.servlet.reception_desk.pay;

import com.xm.entity.Address;
import com.xm.entity.Orders;
import com.xm.entity.ShoppingCart;
import com.xm.service.reception_desk.*;
import com.xm.util.SnowflakeIdUtil;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 新增订单
 *
 * @author 康文程
 * @date 2024-1-8 下午 09:10
 */
@WebServlet("/add/order")
public class AddOrderServlet extends HttpServlet {
    /**
     * 仓库Service
     */
    private final WarehouseService service = new WarehouseService();
    /**
     * 订单Service
     */
    private final OrdersService ordersService = new OrdersService();
    /**
     * 购物车Service
     */
    private final ShoppingCartService shoppingCartService = new ShoppingCartService();
    /**
     * 地址Service
     */
    private final AddressService addressService = new AddressService();
    /**
     * 优惠卷Service
     */
    private final CouponsService couponsService = new CouponsService();

    @SneakyThrows(Exception.class)
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取所有参数
        Map<String, String[]> parameterMap = req.getParameterMap();
        boolean isSelected = ordersService.checkUnselectedAddress(Integer.parseInt(parameterMap.get("informationId")[0]));
        if (isSelected == true){
            LocalDate currentDate = LocalDate.now();
            LocalDate estimatedTimeArrival = currentDate.plusDays(5);

            // 将 LocalDate 转换为 Timestamp
            Timestamp date = Timestamp.valueOf(estimatedTimeArrival.atStartOfDay());

            LocalDateTime currentDateTime = LocalDateTime.now();
            //订单到期时间
            LocalDateTime dateTimeIn15Minutes = currentDateTime.plusMinutes(15);
            Timestamp orderExpirationTime = Timestamp.valueOf(dateTimeIn15Minutes);

            //查询被选中的购物车商品
            List<ShoppingCart> shoppingCartList = shoppingCartService.getSelectedShoppingCartByInformationIdTwo(
                    Integer.parseInt(parameterMap.get("informationId")[0]));
            //查询被选中的地址
            Address deliveryAddress = addressService.
                    getAddressesByInformationIdAndSelected(Integer.parseInt(parameterMap.get("informationId")[0]));


            StringBuilder commodityIds = new StringBuilder();
            StringBuilder specificationIds = new StringBuilder();
            StringBuilder insuranceIds = new StringBuilder();
            for (ShoppingCart shoppingCart : shoppingCartList) {
                commodityIds.append(",").append(shoppingCart.getCommodity().getCommodityId());
                specificationIds.append("|").append(shoppingCart.getSpecificationIds());
                insuranceIds.append("|").append(shoppingCart.getInsuranceIds());
                //删除购物车商品
                shoppingCartService.deleteFromShoppingCart(shoppingCart.getShoppingCartId());
            }
            if (commodityIds.length() > 0) {
                commodityIds.deleteCharAt(0);
                // 删除第一个符号
            }
            if (specificationIds.length() > 0) {
                specificationIds.deleteCharAt(0);
                // 删除第一个符号
            }
            if (insuranceIds.length() > 0) {
                insuranceIds.deleteCharAt(0);
                // 删除第一个符号
            }
            System.out.println(insuranceIds);
            //找出最近到的货仓Id
            Integer warehouseId = service.getAllWarehouses(Double.parseDouble(parameterMap.get("latitude")[0]),
                    Double.parseDouble(parameterMap.get("longitude")[0]));
            //雪花算法生成运单号
            long orderId = SnowflakeIdUtil.generateId(1, 1);
            //优惠卷
            String isUseCoupon = "couponId";
            String couponId = req.getParameter(isUseCoupon);
            //订单
            Orders orders = new Orders();
            orders.setOrdersId("XM"+orderId);
            orders.setFreight(new BigDecimal(parameterMap.get("freight")[0]));
            orders.setPaymentPrice(new BigDecimal(parameterMap.get("totalPrice")[0]));
            orders.setCouponCredit(new BigDecimal(parameterMap.get("couponCredit")[0]));
            orders.setTotalMerchandise(Integer.parseInt(parameterMap.get("totalQuantity")[0]));
            orders.setEstimatedTimeArrival(date);
            orders.setOrderExpirationTime(orderExpirationTime);
            orders.setCommodityIds(commodityIds.toString());
            orders.setAddressId(deliveryAddress.getAddressId());
            orders.setSpecificationIds(specificationIds.toString());
            orders.setInsuranceIds(insuranceIds.toString());
            orders.setWarehouseId(warehouseId);
            orders.setCouponsId(couponId == null ? null : Integer.parseInt(couponId));
            orders.setNumberProducts(parameterMap.get("quantity")[0]);
            System.out.println(orders.getCouponCredit());
            //新增订单
            ordersService.insertOrder(orders);
            //修改使用的优惠卷状态
            if (couponId != null){
                couponsService.updateCouponStatusById(Integer.parseInt(couponId),
                        1);
            }
            //返回订单Id
            resp.getWriter().print(orders.getOrdersId());
        }else{
            //没有选中地址
            resp.getWriter().print(false);
        }
    }

}
